package com.axjy.qg.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("qgService")
public class QgServiceImpl {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;
    /**
     * 减库存
     * @param id
     */
    public    void changeCount(String id){

       RLock rLock= redissonClient.getLock(id);
       try {
           rLock.lock();
           // log.info("{}线程开始抢购",Thread.currentThread().getName());
           BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps("qg:item");
           boolean flag = ops.hasKey(id);
           if (flag == false) {
               throw new RuntimeException("该商品不存在！");
           }
           String count = ops.get(id);
           Integer num = Integer.valueOf(count);
           if (num <= 0) {
               throw new RuntimeException("货物不足！");
           }
           ops.increment(id, -1);
           log.debug("{}线程成功购买商品标号为{}的商品，目前为倒数第{}件商品", Thread.currentThread().getName(), id, count);
       }finally {
           rLock.unlock();
       }

    }




}
